package com.gjy.concurrency.lock;

import lombok.Data;
import org.junit.jupiter.api.Test;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-03-08 09:47:27
 */
public class Lock2Test {

    @Test
    public void test1() throws InterruptedException {
        T1 target = new T1(new MyService());
        Thread t1 = new Thread(target,"T1");
        Thread t2 = new Thread(target,"T2");
        Thread t3 = new Thread(target,"T3");
        Thread t4 = new Thread(target,"T4");
        Thread t5 = new Thread(target,"T5");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }

    private static final class MyService {
        private static final ReentrantLock LOCK = new ReentrantLock();

        public void t1() {
            try {
                LOCK.lock();
                for (int i = 0; i < 5; i++) {
                    System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName() + "_" + i);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                LOCK.unlock();
            }
        }
    }

    @Data
    private static final class T1 implements Runnable {

        private MyService myService;

        public T1(MyService myService) {
            this.myService = myService;
        }

        @Override
        public void run() {
            myService.t1();
        }
    }
}
